#region Usings

using System;
using log4net;
using Karma.Framework.Core.Services.Invoker.Adapter;

#endregion

namespace Karma.Framework.Core.Services.Invoker
{
    public class DefaultInvokerFacade : IInvokerFacade
    {
        private static ILog LOG = LogManager.GetLogger(typeof (DefaultInvokerFacade).Name);

        public DefaultInvokerFacade(IServiceInvoker invoker, IAdapter adapter)
        {
            Adapter = adapter;
            ServiceInvoker = invoker;
        }

        public IAdapter Adapter { get; set; }

        private IServiceInvoker ServiceInvoker { get; set; }

        #region IInvokerFacade Members

        public void Invoke()
        {
            var request = Adapter.ReadRequest();
            try
            {
                Adapter.WriteResponse(request, new ServiceResponse(
                                                   ServiceInvoker.Invoke(request.Service, request.Method,
                                                                         request.Parameters)));
            }
            catch (Exception e)
            {
                LOG.Error(string.Format("Error invoking, Service [{0}.{1}]]", request.Service, request.Method), e);

                e = e.InnerException ?? e;
                var report = !(e.GetType() == typeof (ApplicationException));
                var response = e.InnerException != null
                                   ?
                                       new ServiceResponse(
                                           string.Empty, e.InnerException.Message,
                                           e.InnerException.StackTrace, report)
                                   : new ServiceResponse(
                                         string.Empty, e.Message, e.StackTrace, report);
                Adapter.WriteResponse(request, response);
            }
        }

        #endregion
    }
}